<template>
  <div class="login-page">
    <!-- <div class="left-block"></div> -->
    <div class="sys-info">
      <div class="logo">
        <img src="@/assets/images/logo-light.png" alt="logo">
      </div>
      <div class="system-name">天眼雷达管理系统</div>
    </div>
    <div class="right-block">
      <div class="login-header">
        <!-- <p class="system-name">-</p> -->
        <p>用户登录</p>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginFormRules"
        label-position="top"
        class="login-form"
        style="max-width: 300px"
        @keyup.enter="submitLogin(loginFormRef)"
        @submit.prevent>
        <el-form-item prop="account" label="账号">
          <el-input v-model="loginForm.account" size="large" prefix-icon="User" :maxlength="32" clearable placeholder="输入账号"/>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="loginForm.password" type="password" size="large" prefix-icon="Lock" :maxlength="16" clearable show-password placeholder="输入密码"/>
        </el-form-item>
        <div class="tip-block">
          <el-checkbox v-model="ifRemember">记住账号</el-checkbox>
          <!-- <span class="forget-pwd">忘记密码？</span> -->
        </div>
        <el-form-item>
          <el-button type="primary" class="login-btn" size="large" :loading="loginLoading" @click="submitLogin(loginFormRef)">
            <template #loading>
              <div class="custom-loading">
                <svg class="circular" viewBox="-10, -10, 50, 50">
                  <path
                    class="path"
                    d="
                      M 30 15
                      L 28 17
                      M 25.61 25.61
                      A 15 15, 0, 0, 1, 15 30
                      A 15 15, 0, 1, 1, 27.99 7.5
                      L 15 15
                    "
                    style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"
                  />
                </svg>
              </div>
            </template>
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts" name="Login">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Md5 } from 'ts-md5'
import { login } from '@/api/auth'
import rsa from '@/utils/rsa'

const router = useRouter()
const loginForm = reactive({
  account: '',
  password: ''
})
const loginFormRules = reactive<FormRules>({
  account: [
    { required: true, message: '请输入账号！', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码！', trigger: 'change' }
  ]
})
const loginFormRef = ref<FormInstance>()
const loginLoading = ref(false)
const ifRemember = ref(false)

onMounted(() => {
  if (process.env.NODE_ENV === 'development') {
    loginForm.account = 'admin'
    loginForm.password = 'Admin@123456'
  } else {
    let rem = localStorage.getItem('rememberAccount')
    if (rem) {
      let remObj = JSON.parse(rem)
      if (remObj.account) {
        ifRemember.value = true
        loginForm.account = remObj.account
        loginForm.password = remObj.pwd
      }
    }
  }
})

// 登录
const submitLogin = async (formEl: FormInstance | undefined) => {
  if (loginLoading.value) return
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let rr = new rsa()
      loginLoading.value = true
      let params = {
        username: loginForm.account,
        pwd: rr.rsaEncrypt(loginForm.password), // RSA
      }
      await login(params).then((res: any) => {
        if (res.code === 0) {
          let obj = {
            token: res.data.token,
            userId: res.data.userId,
            key: 'Authorization'
          }
          sessionStorage.setItem('loginUserInfo', JSON.stringify(obj))
          ElMessage({
            message: '登陆成功！正在进入首页...',
            type: 'success',
            duration: 1500
          })
          if (ifRemember.value) {
            localStorage.setItem('rememberAccount', JSON.stringify({
              account: loginForm.account,
              pwd: loginForm.password
            }))
          } else {
            localStorage.removeItem('rememberAccount')
          }
          setTimeout(() => {
            router.push({ name: 'Dashboard' })
          }, 10)
        } else {
          ElMessage({
            message: `${res.msg}`,
            type: 'error',
          })
          loginLoading.value = false
        }
      }).catch(err => {
        console.log(err)
        if (err.response.status === 400) {
          ElMessage({
            message: '登录失败，账号或密码错误，请重试！',
            type: 'error',
          })
        } else {
          ElMessage.error(`接口错误，状态码为 ${err.response.status}。`)
        }
        loginLoading.value = false
      })

      // if (loginForm.account === 'admin' && loginForm.password === 'admin') {
      //   sessionStorage.setItem('loginUserInfo', JSON.stringify({ userAccount: 'admin', userName: '系统管理员', token: '123456' }))
      //   ElMessage({
      //     message: '登陆成功！加载中...',
      //     type: 'success',
      //     duration: 2000
      //   })
      //   setTimeout(() => {
      //     router.push({ name: 'Dashboard' })
      //   }, 1500)
      // } else {
      //   ElMessage({
      //     message: '账号或密码错误！',
      //     type: 'error',
      //   })
      //   loginLoading.value = false
      // }
    }
  })
}
</script>

<style lang="stylus" scoped>
.login-page
  width 100%
  height 100%
  background #01367c
  background-image url('@/assets/images/login-bg.png')
  // background-size cover
  background-repeat no-repeat
  background-position center center
  overflow hidden
  position relative
  .sys-info
    text-align center
    margin-top 50px
    .logo
      width 800px
      margin auto
      img
        width 100%
    .system-name
      color #2e8eff
      font-size 30px
      font-weight bold
  .left-block
    display inline-block
    vertical-align middle
    width 60%
    height 100%
    background-size cover
    background-repeat no-repeat
    background-position center
  .right-block
    // display inline-block
    // vertical-align middle
    // width 40%
    // height 100%
    width 400px
    // max-height 400px
    height 350px
    margin auto
    margin-top 20px
    // position absolute
    // right 15%
    // top 250px
    border-radius 4px
    background rgba(0, 0, 0, .4)
    opacity .9
    border 1px solid #aaa
    color white
    .login-header
      width 300px
      margin auto
      text-align center
      // margin-top 150px
      padding-top 20px
      .system-name
        font-size 20px
        font-weight bold
        letter-spacing 16px
        // color white
      p
        font-weight bold
        font-size 20px
      .logo
        width 30%
    .login-form
      margin auto
      margin-top 20px
      &:deep(.el-form-item__label)
        color white
        &:before
          content ''
      .login-btn
        width 100%
      .custom-loading .circular
        margin-right 6px
        width 18px
        height 18px
        animation loading-rotate 2s linear infinite
      .custom-loading .circular .path
        animation loading-dash 1.5s ease-in-out infinite
        stroke-dasharray 90, 150
        stroke-dashoffset 0
        stroke-width 2
        stroke white
        stroke-linecap round
      .tip-block
        height 16px
        margin-bottom 8px
        .el-checkbox
          height auto
          color white
        .forget-pwd
          float right
          font-size 14px
          color #2e8eff
          cursor pointer
          line-height 1
          &:hover
            opacity .8
</style>
